const cookie         = require('../../util/cookie');
const logger         = require('../../util/log');
const restTemplate   = require('../../util/rest_template');
const config         = require('../config/config');
const Const          = require('../../common/const');
const parser         = require('./parser/parser');
const utils          = require('../../util/utils');

const headers = {
};


class core{

    static async executePageRequest(targetUrl,options){
        //请求页面
        let body = await this.requestPage(targetUrl,options);
        //解析网页
        return await this.doParserVideo(body,options.TYPE);
    }

    /**
     * 请求目标网页
     * @param url 目标网页地址
     * @param requestBasis 任务基础配置
     */
    static async requestPage(url,requestBasis){
        let options = await this.loadBaseOptions(requestBasis);
        options.url = url;

        logger.debug(`Request Options:${JSON.stringify(options)}`);

        return await restTemplate.get(options).catch((error) => {
            throw new Error(`Parser Total. Request url:${url} failed. error:${JSON.stringify(error)}`);
        });
    }

    static async loadBaseOptions(requestBasis){
        let options = {
            url:'',
            headers:(await this.getHeadersAndInjectCookie(requestBasis.cookie)),
            method:requestBasis.METHOD
        };
        //是否使用代理
        if(config.PROXY.need){
            options.proxy = `http://${config.PROXY.host}:${config.PROXY.port}`
        }
        //如果是post,则设置body参数
        if(requestBasis.METHOD === 'POST'){
            options.body = JSON.stringify(requestBasis.body);
        }
        return options;
    }

    static async getHeadersAndInjectCookie(cookie){
        // let cookie = await this.getCookie();
        headers['Cookie'] = cookie;
        headers['cookie'] = cookie;
        return headers;
    }

    /**
     * 获取cookie
     */
    static async getCookie(){
        return await new cookie().getCookieByWebsite();
    }

    /**
     * 执行解析器 获取采集内容
     * @param htmlString 网页源码
     * @param type 任务类型
     */
    static async doParserVideo(htmlString,type){
        return await parser.runCode(type,htmlString).catch((error) => {
            logger.err(`Do Parser Failed !!! Error Message:[${error}]`);
            return {
                code:Const._RETCODE_HANDLER_FAILED,
                message:error,
                data:{
                    rows:[],
                    code:Const._RETCODE_HANDLER_FAILED
                }
            }
        });
    }
}

module.exports = core;
